﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DDNY.WebPortals.Common;
using KeywordsBasedMVCPortal.Models;
using System.Xml.Linq;
using System.Xml.XPath;
using System.Web.Caching;


namespace VideoPortal.Controllers
{
    public class ApplicationController : Controller
    {
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            ViewBag.MainFeedTypes = YoutubeHelper.GetMainYoutubeFeedTypes();
            //ViewBag.Playlists = YoutubeHelper.GetAllPlaylists();
            ViewBag.Recommended = YoutubeHelper.GetRecommendedVideos("");
            ViewBag.Categories = GetAllCategories();
            ViewBag.Robots = SEOHelper.Index;

            WebLink randomLink = LinkManager.GetRandomResLink();
            ViewBag.ResLink = string.Format("<a href='{0}'>{1}</a>", randomLink.LinkUrl, randomLink.Anchor);


        }

        List<VideoCategory> GetAllCategories()
        {
            List<VideoCategory> result = null;
            string cacheKey = "AllCategories";
            if (HttpContext.Cache[cacheKey] != null)
            {
                result = (List<VideoCategory>)HttpContext.Cache[cacheKey];
            }
            else
            {



                string path = System.Web.HttpContext.Current.Server.MapPath(@"~/App_Data/categories.xml");

                var categoryItems = XDocument.Load(path).Root.Nodes();
                result = new List<VideoCategory>();
                foreach (var categoryElement in categoryItems)
                {
                    XElement castedElement = categoryElement as XElement;
                    if (!castedElement.ToString().Contains("deprecated"))
                    {
                        VideoCategory catToAdd = new VideoCategory()
                        {
                            Label = castedElement.Attribute("label").Value,
                            Term = castedElement.Attribute("term").Value
                        };
                        result.Add(catToAdd);
                    }
                    
                }
                result = result.OrderBy(a => a.Label).ToList();
                HttpContext.Cache.Add(cacheKey, result, null, DateTime.Now.AddHours(2), Cache.NoSlidingExpiration, CacheItemPriority.Default, null);
            }
            return result;
        }
    }
}
